<?php
/**
 * author:歪妻
 * Date: 2020/11/11 0011
 */

require_once 'lib/common.php';
require_once 'lib/list-posts.php';

session_start();
// 不要让非身份验证用户看到此屏幕
if (!isLoggedIn())
{
    redirectAndExit('index.php');
}

// 连接到数据库，运行查询
$pdo = getPDO();
$posts = getAllPosts($pdo);

if ($_POST)
{
    $deleteResponse = $_POST['delete-post'];
    if ($deleteResponse)
    {
        $keys = array_keys($deleteResponse);
        $deletePostId = $keys[0];
        if ($deletePostId)
        {
            deletePost($pdo, $deletePostId);
            redirectAndExit('list-posts.php');
        }
    }
}

?>
<!DOCTYPE html>
<html>
<head>
    <title>博客应用 | 博客文章</title>
    <?php require 'templates/head.php' ?>
</head>
<body>
<?php require 'templates/title.php' ?>
<h1>帖子列表</h1>
<p>你有 <?php echo count($posts) ?> 帖子.

<form method="post">
    <table id="post-list">
        <thead>
        <tr>
            <th>主题</th>
            <th>创建日期</th>
            <th>评论</th>
            <th />
            <th />
        </tr>
        </thead>
        <tbody>
        <?php foreach ($posts as $post): ?>
            <tr>
                <td>
                    <a href="view-post.php?post_id=<?php echo $post['id']?>">
                        <?php echo htmlEscape($post['title']) ?></a>
                </td>

                <td>
                    <a></a>
                    <?php echo convertSqlDate($post['created_at']) ?>
                </td>
                <td>
                    <?php echo $post['comment_count'] ?>
                </td>
                <td>
                    <a href="edit-post.php?post_id=<?php echo $post['id']?>">修改</a>
                </td>
                <td>
                    <input type="submit" name="delete-post[<?php echo $post['id']?>]" value="删除"/>
                </td>
            </tr>
        <?php endforeach ?>

        </tbody>
    </table>
</form>
</body>
</html>